<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="fromData"
        label-width="100px"
        class="demo-ruleForm"
        style="width: 100%"
      >
        <el-form-item label="学科" prop="subjectID">
          <el-select
            v-model="ruleForm.subjectID"
            placeholder="请选择学科"
            @change="change"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in SubjectList"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录" prop="catalogID">
          <el-select v-model="ruleForm.catalogID" placeholder="请选择目录">
            <el-option
              :label="item.directoryName"
              :value="item.id"
              v-for="item in catalogList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="ruleForm.enterpriseID" placeholder="请选择企业">
            <el-option
              :label="item.shortName"
              :value="item.id"
              v-for="item in ruleForm.enterprise"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select
            v-model="ruleForm.province"
            placeholder="请选择"
            @change="handleChange"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="(item, index) in provinces"
              :key="index"
            ></el-option>
          </el-select>
          <el-select
            v-model="ruleForm.city"
            placeholder="请选择"
            style="margin-left: 10px"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="(item, index) in citys"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-select v-model="ruleForm.direction" placeholder="请选择方向">
            <el-option
              :label="item"
              :value="item"
              v-for="(item, index) in direction"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型" prop="questionType">
          <el-radio-group v-model="ruleForm.questionType" @change="changeRadio">
            <el-radio
              :label="item.value"
              v-for="item in questionType"
              :key="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="ruleForm.difficulty">
            <el-radio
              :label="item.value"
              v-for="item in difficulty"
              :key="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干" prop="question">
          <!-- 富文本编辑器组件 -->
          <quill-editor v-model="ruleForm.question"></quill-editor>
        </el-form-item>
        <el-form-item label="选项" v-show="showBtn">
          <el-radio-group v-model="selePage" v-if="ruleForm.questionType === 1">
            <div
              class="radio"
              style="margin-bottom: 30px"
              v-for="(item, index) in ruleForm.options"
              :key="index"
            >
              <el-radio :label="item.code" :key="item.id" @change="RadioChange">
                {{ item.code }}: <el-input v-model="item.title"></el-input>
                <el-upload
                  action="https://jsonplaceholder.typicode.com/posts/"
                  list-type="picture-card"
                  style="display: inline-block"
                >
                  上传图片
                </el-upload>
              </el-radio>
            </div>
          </el-radio-group>
          <el-checkbox-group
            v-else-if="ruleForm.questionType === 2"
            v-model="selePagelist"
          >
            <div
              class="radio"
              style="margin-bottom: 30px"
              v-for="(item, index) in ruleForm.options"
              :key="index"
            >
              <el-checkbox
                :label="item.code"
                :key="item.id"
                @change="checkChange($event, item)"
              >
                {{ item.code }}: <el-input v-model="item.title"></el-input>
                <el-upload
                  action="https://jsonplaceholder.typicode.com/posts/"
                  list-type="picture-card"
                  style="display: inline-block"
                >
                  上传图片
                </el-upload>
              </el-checkbox>
            </div>
          </el-checkbox-group>
          <div>
            <el-button
              type="danger"
              icon="el-icon-plus"
              :disabled="disabled"
              @click="add()"
              >增加选项和答案</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="解析视频" class="e-input">
          <el-input v-model="ruleForm.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析" prop="answer">
          <quill-editor v-model="ruleForm.answer"></quill-editor>
        </el-form-item>
        <el-form-item label="题目备注" class="e-input">
          <el-input type="textarea" v-model="ruleForm.remarks"></el-input>
        </el-form-item>
        <el-form-item label="试题标签">
          <el-select
            v-model="ruleForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择试题标签"
          >
            <el-option
              v-for="item in ruleForm.tagsList"
              :key="item.id"
              :label="item.tagName"
              :value="item.tagName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            :type="questiondata.id ? 'success' : 'primary'"
            @click="submit"
            >{{ questiondata.id ? "确定修改" : "确定提交" }}</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 获取学科
import { simple as getSubjecsimple } from '@/api/hmmm/subjects'
// 获取目录
import { list as getcatalogListsimple } from '@/api/hmmm/directorys'
// 获取企业
import { list as getenterprise } from '@/api/hmmm/companys'
// 获取城市
import { provinces, citys } from '@/api/hmmm/citys'
// 获取方向
import { direction, difficulty, questionType } from '@/api/hmmm/constants'
// 获取标签
import { list as getTagsList } from '@/api/hmmm/tags'
// 添加试题录入    // 获取detail
import { add as getqiestionsAdd, detail as getqiestionsdetail, update } from '@/api/hmmm/questions'

export default {
  name: 'questions',
  data () {
    return {
      ruleForm: {
        enterprise: [], // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '无', // 答案解析
        remarks: '无', // 题目备注
        tags: '', // 试题标签
        isPerfect: false, // 是否精选题
        subjectID: '', // 学科ID
        catalogID: '', // 目录ID
        enterpriseID: '', // 企业ID
        Pagetext: '', // 选中单选文本框的值
        tagsList: [], // 试题标签列表
        options: [
          {
            id: 1, code: 'A', title: '', img: '', isRight: false
          },
          {
            id: 2, code: 'B', title: '', img: '', isRight: false
          },
          {
            id: 3, code: 'C', title: '', img: '', isRight: false
          },
          {
            id: 4, code: 'D', title: '', img: '', isRight: false
          }
        ] // 选项

      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请选择题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'change' }
        ]

      },
      provinces: [], // 所有城市
      citys: [], // 城市下地区
      city: '', // 选择的城市
      county: '', // 县级市
      direction: [], // 获取方向
      difficulty: '', // 难度
      questionType: '', // 获取题型
      disabled: false, // 是否禁用按钮
      showBtn: true, // 是否显示
      questiondata: {
        id: '' // 题库id
      },
      SubjectList: [], // 学科列表
      catalogList: [], // 目录列表
      selePage: '', // 单选
      selePagelist: [], // 多选
      counts: ''
    }
  },
  async created () {
    this.getSubjecsimple()
    await this.getenterprise()
    await this.getenterprise(this.counts)
    // 获取城市
    this.provinces = provinces()
    // console.log(this.provinces)
    // 获取方向
    this.direction = direction
    // 获取难度
    this.difficulty = difficulty
    // 获取题型
    this.questionType = questionType
    this.changeRadio()
    // 获取id
    const id = this.$route.query.id
    this.questiondata.id = id
    console.log(this.questiondata.id)
    // 判断是否有id
    if (this.questiondata.id) {
      // 必须等他获取数据才能进行下一步
      await this.getqiestionsdetail()
      this.getcatalogListyssimple()
    }
  },

  methods: {
    // 获取学科列表
    async getSubjecsimple () {
      const { data } = await getSubjecsimple()
      // console.log(data)
      this.SubjectList = data
    },
    // 获取目录列表
    async  getcatalogListyssimple () {
      const { data: { items } } = await getcatalogListsimple({
        subjectID: this.ruleForm.subjectID
      })
      // console.log(items)
      this.catalogList = items
    },
    // 学科发生改变立即获取数据
    change () {
      this.getcatalogListyssimple()
      // 获取标签
      this.getTagsList()
    },
    // 获取企业
    async getenterprise (count) {
      const { data: { items, counts } } = await getenterprise({ pagesize: count })
      // console.log(counts)
      this.counts = counts
      console.log(items)
      this.ruleForm.enterprise = items
    },
    //
    handleChange (e) {
      // console.log(e)
      this.citys = citys(e)
    },
    // 改变
    changeRadio () {
      // 如果等于1禁用按钮 显示单选框 清空复选框的内容
      if (this.ruleForm.questionType === 1) {
        this.disabled = true
        this.showBtn = true
        this.selePagelist = []
        // 等于2 按钮解除禁用，显示复选框，清空单选框的内容
      } else if (this.ruleForm.questionType === 2) {
        this.disabled = false
        this.showBtn = true
        this.selePage = ''
      } else if (this.ruleForm.questionType === 3) {
        this.showBtn = false
      }
    },
    // 新增文本框
    add () {
      let id = this.ruleForm.options[this.ruleForm.options.length - 1].id
      let code = this.ruleForm.options[this.ruleForm.options.length - 1].code.charCodeAt() // string.charCodeAt   将字符串转换成 ASCII码
      id++
      code++
      // String.fromCharCode(code) 将 ASCII码转换成字符
      this.ruleForm.options.push({ id: id, code: String.fromCharCode(code), title: '', img: '', isRight: false })
    },
    // 单选 事件
    RadioChange (e) {
      const RadioArr = this.ruleForm.options.filter(t => t.code === e)
      this.ruleForm.options.forEach(t => {
        t.isRight = false
      })
      RadioArr[0].isRight = true
    },
    // 多选事件
    checkChange (e, item) {
      console.log(e)
      const checkArr = this.ruleForm.options.filter(t => t.code === item.code)
      checkArr[0].isRight = e
      console.log(checkArr)
    },
    // 获取标签列表
    async getTagsList () {
      const { data: { items } } = await getTagsList({
        subjectID: this.ruleForm.subjectID
      })
      console.log(items)
      this.ruleForm.tagsList = items
    },
    // 提交
    async submit () {
      this.$refs.fromData.validate(async (isOk) => {
        const tags = this.ruleForm.tags.join(',')
        const arr = JSON.parse(JSON.stringify(this.ruleForm))
        arr.questionType = arr.questionType.toString()
        arr.difficulty = arr.difficulty.toString()
        arr.tags = tags
        if (!isOk) return this.$message.error('请选择必填项')

        if (this.questiondata.id) {
          try {
            await update({ id: this.questiondata, ...arr })
            this.$message.success('修改成功')
          } catch (error) {
            this.$message.error('修改失败')
          }
        } else {
          try {
            await getqiestionsAdd(arr)
            this.$message.success('试题录入成功')
          } catch (error) {
            this.$message.error('试题录入失败')
            console.log(error)
          }
        }

        //  清空表单
        this.$refs.fromData.resetFields()
        this.formData = this.$options.data().formData
        this.$router.push('/questions/list')
      })
    },
    async getqiestionsdetail () {
      // 获取到详情
      const { data } = await getqiestionsdetail(this.questiondata)
      console.log(data)
      // 深拷贝值
      this.ruleForm = JSON.parse(JSON.stringify(data))
      // 强制转换为数字
      this.ruleForm.questionType = Number(this.ruleForm.questionType)
      // 强制转换为数字
      this.ruleForm.difficulty = Number(this.ruleForm.difficulty)
      // 将字符串转换为数字
      this.ruleForm.tags = this.ruleForm.tags.split(' ')
      // 把选中的数组选择出来
      const a = this.ruleForm.options.filter(t => t.isRight === 1)
      // 得到多选的选项
      this.selePagelist.push(...a.map(t => t.code))
      // 得到单选的选项
      this.selePage = a[0].code
    }

  },
  computed: {

  }

}
</script>

<style scoped lang='scss'>
.box-card {
  margin: 15px;
}
.el-select--medium {
  width: 30%;
}
::v-deep .ql-container {
  height: 200px;
}
.radio {
  margin-top: 20px;
}
.e-input {
  width: 50%;
}
::v-deep .el-upload--picture-card {
  height: 57px !important;
  line-height: 57px !important;
  margin-left: 15px;
  vertical-align: 0px !important;
}
</style>
